import { Request, Response, NextFunction } from "express";
import { connection } from "@/services/database";
import { generateUpdateFields, checkIsStudentBelongUser, checkIsAdmin, getcontactPhoneNumberInfo } from "@/utils/sql";

interface Params {
	user_id: number;
	contact_phone_number: string;
}
export default async (request: Request, response: Response, next: NextFunction) => {
	try {
		const callerId = response.locals.user.id;
		const params = request.body as unknown as Params;
		if (callerId != params.user_id && !(await checkIsStudentBelongUser(callerId, params.user_id)) && !(await checkIsAdmin(callerId))) throw new Error("无权操作");
		const contactPhoneNumberBelongings = await getcontactPhoneNumberInfo(params.contact_phone_number);
		if (!contactPhoneNumberBelongings) throw new Error("联系人手机号无效");
		const [results] = (await connection.execute("SELECT contact_phone_number FROM student WHERE user_id = :user_id", params)) as any;
		if (!results[0]) throw new Error("未查询到学生");
		if (results[0].contact_phone_number !== null) throw new Error("不可重复绑定联系人手机号");
		(await connection.execute("UPDATE student SET " + generateUpdateFields({ contact_phone_number: params.contact_phone_number }) + " WHERE user_id = :user_id", params)) as any;
		response.json({ data: null, message: "成功" });
	} catch (error) {
		response.statusCode = 400;
		next(error);
	}
};
